/**
 * 内容脚本
 * 负责页面内容提取、翻译和UI渲染
 * 版本: v2.0 - 修复CSS选择器兼容性问题
 */

class ContentTranslator {
    constructor() {
        this.translatedSections = new Set();
        this.isTranslating = false;
        this.config = null;
        this.floatingButton = null;
        this.translationPanel = null;

        this.init();
    }

    async init() {
        try {
            // 等待页面加载完成
            if (document.readyState !== 'complete') {
                await new Promise(resolve => {
                    window.addEventListener('load', resolve);
                });
            }

            // 加载配置
            await this.loadConfig();

            // 创建浮动按钮
            this.createFloatingButton();

            // 监听来自background的消息
            this.messageListener = this.handleMessage.bind(this);
            chrome.runtime.onMessage.addListener(this.messageListener);

            // 检查是否自动翻译
            if (this.config.autoTranslate) {
                setTimeout(() => {
                    this.translatePage();
                }, 1000);
            }

            console.log('Content translator initialized - v2.0 (CSS Selector Fix)');
        } catch (error) {
            console.error('Failed to initialize content translator:', error);
        }
    }

    /**
     * 加载配置
     */
    async loadConfig() {
        try {
            this.config = await chrome.storage.sync.get({
                translationEngine: 'openai',
                sourceLanguage: 'auto',
                targetLanguage: 'zh-CN',
                displayMode: 'below',
                autoTranslate: false,
                debugMode: false
            });
        } catch (error) {
            console.error('Failed to load config:', error);
            // 使用默认配置
            this.config = {
                translationEngine: 'openai',
                sourceLanguage: 'auto',
                targetLanguage: 'zh-CN',
                displayMode: 'below',
                autoTranslate: false,
                debugMode: false
            };
        }
    }

    /**
     * 创建浮动按钮
     */
    createFloatingButton() {
        // 检查是否已存在
        if (document.getElementById('translator-floating-btn')) {
            return;
        }

        const button = document.createElement('div');
        button.id = 'translator-floating-btn';
        button.innerHTML = `
            <div class="translator-btn-icon">🌐</div>
            <div class="translator-btn-text">翻译</div>
        `;

        // 添加样式
        button.style.cssText = `
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            z-index: 10000;
            transition: all 0.3s ease;
            opacity: 0.9;
        `;

        // 悬停效果
        button.addEventListener('mouseenter', () => {
            button.style.transform = 'scale(1.1)';
            button.style.opacity = '1';
        });

        button.addEventListener('mouseleave', () => {
            button.style.transform = 'scale(1)';
            button.style.opacity = '0.9';
        });

        // 点击事件
        button.addEventListener('click', () => {
            this.translatePage();
        });

        document.body.appendChild(button);
        this.floatingButton = button;

        // 添加图标和文字样式
        const style = document.createElement('style');
        style.textContent = `
            #translator-floating-btn .translator-btn-icon {
                font-size: 24px;
                line-height: 1;
                margin-bottom: 2px;
            }
            #translator-floating-btn .translator-btn-text {
                font-size: 12px;
                font-weight: bold;
                color: white;
                line-height: 1;
            }

            @keyframes translatorPulse {
                0% { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); }
                50% { box-shadow: 0 4px 30px rgba(102, 126, 234, 0.6); }
                100% { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); }
            }

            .translator-translating {
                animation: translatorPulse 2s infinite;
            }
        `;
        document.head.appendChild(style);
    }

    /**
     * 处理消息
     */
    async handleMessage(request, sender, sendResponse) {
        try {
            if (request.action === 'translate') {
                await this.translatePage();
                sendResponse({ success: true });
            } else if (request.action === 'configUpdated') {
                await this.loadConfig();
            }
        } catch (error) {
            console.error('Message handling error:', error);
            sendResponse({ success: false, error: error.message });
        }
    }

    /**
     * 翻译整个页面
     */
    async translatePage() {
        // 检查扩展上下文是否有效
        if (!this.isExtensionContextValid()) {
            this.showError('扩展上下文已失效，请刷新页面重试');
            return;
        }

        if (this.isTranslating) {
            console.log('Translation already in progress');
            return;
        }

        this.isTranslating = true;
        this.showLoadingState();

        try {
            console.log('🔄 Starting translation process...');

            // 提取页面内容
            const sections = this.extractProblemContent();
            console.log(`📋 Extracted ${sections.length} sections:`, sections.map(s => ({ type: s.type, textLength: s.text.length })));

            if (sections.length === 0) {
                console.error('❌ No sections found to translate');
                this.showError('未找到可翻译的内容');
                return;
            }

            // 更新浮动按钮状态
            if (this.floatingButton) {
                this.floatingButton.classList.add('translator-translating');
                const btnText = this.floatingButton.querySelector('.translator-btn-text');
                if (btnText) btnText.textContent = '翻译中';
            }

            console.log('📤 Sending translation request...');
            // 发送翻译请求
            const results = await this.sendTranslationRequest(sections);
            console.log('📥 Translation request completed, received results:', results.length);

            // 渲染翻译结果
            console.log('🎨 Rendering translation results...');
            await this.renderTranslationResults(sections, results);
            console.log('✅ Translation results rendered successfully');

            // 显示成功消息
            this.showSuccessMessage();
            console.log('✅ Success message shown');

        } catch (error) {
            console.error('Translation failed:', error);
            this.showError('翻译失败: ' + error.message);
        } finally {
            console.log('🔚 Translation process finished, cleaning up...');
            this.isTranslating = false;
            this.hideLoadingState();

            // 恢复浮动按钮状态
            if (this.floatingButton) {
                this.floatingButton.classList.remove('translator-translating');
                const btnText = this.floatingButton.querySelector('.translator-btn-text');
                if (btnText) btnText.textContent = '翻译';
            }
            console.log('✅ Cleanup completed, isTranslating reset to:', this.isTranslating);
        }
    }

    /**
     * 提取题目内容
     */
    extractProblemContent() {
        console.log('🔍 Starting content extraction...');

        // 检测当前网站
        const isCodeforces = window.location.hostname.includes('codeforces.com');
        const isAtCoder = window.location.hostname.includes('atcoder.jp');

        console.log('🌐 Site detection:', { isCodeforces, isAtCoder, hostname: window.location.hostname });

        let problemStatement = null;
        let sections = [];

        if (isCodeforces) {
            console.log('📋 Using Codeforces extraction logic...');
            problemStatement = document.querySelector('.problem-statement');

            if (problemStatement) {
                const text = problemStatement.innerText || problemStatement.textContent;
                if (text && text.trim()) {
                    sections.push({
                        type: 'fulltext',
                        element: problemStatement,
                        text: text
                    });
                }
            }
        } else if (isAtCoder) {
            console.log('📋 Using AtCoder extraction logic...');
            return this.extractAtCoderContent();
        }

        if (sections.length === 0) {
            console.error('❌ No content found for this site');
            console.log('🔍 Available elements:', this.debugAvailableElements());
            return [];
        }

        const text = sections[0].text;
        console.log('=== 提取的题目原文（不做任何处理）===');
        console.log('站点类型:', isCodeforces ? 'Codeforces' : isAtCoder ? 'AtCoder' : 'Unknown');
        console.log('文本长度:', text.length);
        console.log('是否包含换行符:', text.includes('\n'));
        console.log('文本预览:', text.substring(0, 200) + '...');
        console.log('==============================');

        return sections;
    }

    // 调试可用元素
    debugAvailableElements() {
        const commonSelectors = [
            '.problem-statement',
            '#task-statement',
            '.task-statement',
            '[id*="task"]',
            '[id*="problem"]',
            '.col-12',
            '.span12',
            'main',
            'article'
        ];

        const found = {};
        commonSelectors.forEach(selector => {
            const element = document.querySelector(selector);
            if (element) {
                found[selector] = {
                    exists: true,
                    textLength: (element.innerText || element.textContent || '').length,
                    className: element.className,
                    id: element.id
                };
            }
        });

        console.log('🔍 Available page elements:', found);
        return found;
    }

    /**
     * 提取 Codeforces 内容
     */
    extractCodeforcesContent() {
        const sections = [];

        // 标题
        const titleElement = document.querySelector('.problem-statement .header .title');
        if (titleElement) {
            sections.push({
                type: 'title',
                element: titleElement,
                text: titleElement.textContent.trim()
            });
        }

        // 问题陈述
        const statementElement = document.querySelector('.problem-statement .header div div');
        if (statementElement) {
            const text = statementElement.textContent.trim();
            if (text && !sections.find(s => s.text === text)) {
                sections.push({
                    type: 'statement',
                    element: statementElement,
                    text: text
                });
            }
        }

        // 输入格式
        const inputSpecElement = document.querySelector('.problem-statement .input-specification .section-title');
        if (inputSpecElement) {
            const inputDescription = inputSpecElement.nextElementSibling;
            if (inputDescription) {
                sections.push({
                    type: 'input',
                    element: inputDescription,
                    text: inputDescription.textContent.trim()
                });
            }
        }

        // 输出格式
        const outputSpecElement = document.querySelector('.problem-statement .output-specification .section-title');
        if (outputSpecElement) {
            const outputDescription = outputSpecElement.nextElementSibling;
            if (outputDescription) {
                sections.push({
                    type: 'output',
                    element: outputDescription,
                    text: outputDescription.textContent.trim()
                });
            }
        }

        // 样例输入输出
        const sampleTests = document.querySelectorAll('.sample-test');
        sampleTests.forEach((test, index) => {
            const inputDiv = test.querySelector('.input');
            const outputDiv = test.querySelector('.output');

            if (inputDiv) {
                const preElement = inputDiv.querySelector('pre');
                if (preElement) {
                    sections.push({
                        type: 'sample-input',
                        element: preElement,
                        text: preElement.textContent.trim(),
                        metadata: { index: index + 1 }
                    });
                }
            }

            if (outputDiv) {
                const preElement = outputDiv.querySelector('pre');
                if (preElement) {
                    sections.push({
                        type: 'sample-output',
                        element: preElement,
                        text: preElement.textContent.trim(),
                        metadata: { index: index + 1 }
                    });
                }
            }
        });

        // 注意事项
        const noteElement = document.querySelector('.problem-statement .note');
        if (noteElement) {
            sections.push({
                type: 'note',
                element: noteElement,
                text: noteElement.textContent.trim()
            });
        }

        return sections;
    }

    /**
     * 提取 AtCoder 内容
     */
    extractAtCoderContent() {
        console.log('📋 Starting AtCoder content extraction...');

        try {
            // 寻找AtCoder题目内容的主要容器
            let statementElement = document.getElementById('task-statement');

            if (!statementElement) {
                // 尝试其他可能的选择器
                statementElement = document.querySelector('.task-statement, .statement, main, .main');
            }

            if (!statementElement) {
                console.error('❌ No AtCoder statement element found');
                console.log('🔍 Available elements:', this.debugAvailableElements());
                return [];
            }

            console.log('✅ Found AtCoder statement element:', statementElement);

            // 提取全文内容
            const text = statementElement.innerText || statementElement.textContent;

            if (!text || !text.trim()) {
                console.error('❌ AtCoder statement text is empty');
                return [];
            }

            console.log('=== 提取的AtCoder题目原文 ===');
            console.log('文本长度:', text.length);
            console.log('是否包含换行符:', text.includes('\n'));
            console.log('文本预览:', text.substring(0, 200) + '...');
            console.log('=========================');

            // 返回单个全文section
            return [{
                type: 'fulltext',
                element: statementElement,
                text: text.trim()
            }];

        } catch (error) {
            console.error('❌ Error extracting AtCoder content:', error);
            console.log('🔍 Available elements:', this.debugAvailableElements());
            return [];
        }
    }

    /**
     * 从AtCoder声明中提取内容
     */
    extractAtCoderStatement(statementElement, sections) {
        try {
            // 获取所有段落
            const paragraphs = statementElement.querySelectorAll('p');
            paragraphs.forEach(p => {
                const text = p.textContent.trim();
                if (text && !text.includes('Problem Statement') &&
                    !text.includes('制約') &&
                    !text.includes('Input') &&
                    !text.includes('Output') &&
                    !text.includes('Sample Input') &&
                    !text.includes('Sample Output') &&
                    !text.includes('入力') &&
                    !text.includes('出力') &&
                    !text.includes('入力例') &&
                    !text.includes('出力例')) {
                    sections.push({
                        type: 'statement',
                        element: p,
                        text: text
                    });
                }
            });

            // 输入格式
            const inputSection = this.findInputSection(statementElement);
            if (inputSection) {
                const inputContent = inputSection.nextElementSibling;
                if (inputContent) {
                    sections.push({
                        type: 'input',
                        element: inputContent,
                        text: inputContent.textContent.trim()
                    });
                }
            }

            // 输出格式
            const outputSection = this.findOutputSection(statementElement);
            if (outputSection) {
                const outputContent = outputSection.nextElementSibling;
                if (outputContent) {
                    sections.push({
                        type: 'output',
                        element: outputContent,
                        text: outputContent.textContent.trim()
                    });
                }
            }

            // 样例
            const sampleTests = this.findSampleTests(statementElement);
            sampleTests.forEach((sample, index) => {
                if (sample.input) {
                    sections.push({
                        type: 'sample-input',
                        element: sample.input,
                        text: sample.input.textContent.trim(),
                        metadata: { index: sample.index }
                    });
                }

                if (sample.output) {
                    sections.push({
                        type: 'sample-output',
                        element: sample.output,
                        text: sample.output.textContent.trim(),
                        metadata: { index: sample.index }
                    });
                }
            });
        } catch (error) {
            console.error('Error extracting AtCoder statement:', error);
        }
    }

    /**
     * AtCoder 内容提取的备用方法
     */
    extractAtCoderContentFallback(sections) {
        try {
            // 尝试直接查找代码块作为样例
            const allPreElements = document.querySelectorAll('pre');
            let sampleIndex = 0;

            allPreElements.forEach((pre, index) => {
                const text = pre.textContent.trim();
                if (text) {
                    // 简单判断是否是样例（通常是数字或简单格式）
                    if (text.includes('\n') && text.length < 1000) {
                        sampleIndex++;
                        const isInput = index % 2 === 0; // 假设奇数是输入，偶数是输出

                        sections.push({
                            type: isInput ? 'sample-input' : 'sample-output',
                            element: pre,
                            text: text,
                            metadata: { index: sampleIndex }
                        });
                    }
                }
            });
        } catch (error) {
            console.error('Error in fallback extraction:', error);
        }
    }

    /**
     * 发送翻译请求
     */
    async sendTranslationRequest(sections) {
        console.log('🔗 sendTranslationRequest called with', sections.length, 'sections');

        // 检查扩展上下文是否有效
        if (!this.isExtensionContextValid()) {
            console.error('❌ Extension context invalid');
            throw new Error('扩展上下文已失效，请刷新页面重试');
        }

        console.log('✅ Extension context valid');

        // 简化：将所有内容合并为一个文本
        const fullText = sections.map(s => s.text).join('\n\n');
        console.log('📝 Combined text length:', fullText.length);

        if (!fullText.trim()) {
            throw new Error('没有找到可翻译的内容');
        }

        console.log('📤 Sending translation request...');
        console.log('📤 Message details:', {
            action: 'translate',
            dataLength: fullText.length,
            dataPreview: fullText.substring(0, 100) + (fullText.length > 100 ? '...' : ''),
            timestamp: new Date().toISOString()
        });

        try {
            console.log('🔍 Checking chrome.runtime availability...');
            console.log('🔍 Chrome runtime details:', {
                hasRuntime: !!chrome.runtime,
                hasId: !!chrome.runtime?.id,
                runtimeId: chrome.runtime?.id,
                hasLastError: !!chrome.runtime.lastError,
                lastError: chrome.runtime.lastError
            });

            if (!chrome.runtime) {
                console.error('❌ chrome.runtime is not available');
                throw new Error('Chrome runtime not available');
            }

            if (!chrome.runtime.id) {
                console.error('❌ chrome.runtime.id is not available');
                throw new Error('Extension context invalid');
            }

            console.log('🚀 Attempting background script call...');

            // 使用Promise包装异步翻译请求，但增加更长的超时时间
            const response = await new Promise((resolve, reject) => {
                console.log('📤 Setting up message with callback...');

                const timeoutId = setTimeout(() => {
                    console.warn('⏰ Message timeout after 60 seconds');
                    reject(new Error('Background script消息超时 (60秒)'));
                }, 60000); // 增加到60秒

                try {
                    chrome.runtime.sendMessage({
                        action: 'translate',
                        data: fullText
                    }, (response) => {
                        clearTimeout(timeoutId);
                        console.log('📬 Message callback triggered');
                        console.log('📬 Chrome runtime lastError:', chrome.runtime.lastError);
                        console.log('📬 Response received:', response);

                        if (chrome.runtime.lastError) {
                            console.error('❌ Chrome runtime error in callback:', chrome.runtime.lastError);
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(response);
                        }
                    });
                } catch (sendError) {
                    clearTimeout(timeoutId);
                    console.error('❌ Error sending message:', sendError);
                    reject(sendError);
                }
            });

            console.log('📥 Received response from background script:', response);

            if (response && response.success) {
                console.log('✅ Translation successful');
                // 为每个section返回相同的翻译结果
                return sections.map(() => response.translation);
            } else {
                console.error('❌ Translation failed:', response?.error);
                throw new Error(response?.error || '翻译请求失败');
            }
        } catch (error) {
            console.error('❌ Translation request error:', error);
            console.error('❌ Error details:', {
                name: error.name,
                message: error.message,
                stack: error.stack,
                isTimeout: error.message.includes('超时'),
                isLastError: !!chrome.runtime.lastError,
                lastError: chrome.runtime.lastError
            });

            // 直接抛出错误，不使用fallback（会被CORS阻止）
            throw error;
        }
    }

    /**
     * 直接调用有道API (fallback机制)
     */
    async directAPICall(text) {
        console.log('🌐 Making direct API call to Youdao...');

        try {
            // 获取配置
            const config = await chrome.storage.sync.get({
                youdaoApiKey: '',
                youdaoAppSecret: ''
            });

            if (!config.youdaoApiKey || !config.youdaoAppSecret) {
                throw new Error('有道翻译配置不完整，请检查设置');
            }

            console.log('🔧 Using config:', {
                hasApiKey: !!config.youdaoApiKey,
                apiKeyLength: config.youdaoApiKey.length,
                hasAppSecret: !!config.youdaoAppSecret,
                appSecretLength: config.youdaoAppSecret.length
            });

            // 预处理文本
            const processedText = this.preprocessText(text);
            console.log('🔧 Text preprocessed, length:', processedText.length);

            // 生成v3签名参数
            const salt = this.generateUUID();
            const curtime = Math.floor(Date.now() / 1000).toString();
            const sign = await this.generateYoudaoSignV3(processedText, salt, curtime, config.youdaoApiKey, config.youdaoAppSecret);

            console.log('🔐 Generated signature:', {
                salt: salt,
                curtime: curtime,
                signLength: sign.length
            });

            // 构建请求参数
            const params = new URLSearchParams();
            params.append('q', processedText);
            params.append('from', 'auto');
            params.append('to', 'zh-CHS');
            params.append('appKey', config.youdaoApiKey);
            params.append('salt', salt);
            params.append('curtime', curtime);
            params.append('signType', 'v3');
            params.append('sign', sign);

            console.log('🌐 Sending direct API request to Youdao...');
            console.log('📋 Request details:', {
                url: 'https://openapi.youdao.com/api',
                method: 'POST',
                contentLength: params.toString().length,
                textLength: processedText.length
            });

            const response = await fetch('https://openapi.youdao.com/api', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params.toString()
            });

            console.log('📥 API response status:', response.status, response.statusText);

            if (!response.ok) {
                const errorText = await response.text();
                console.error('❌ API request failed:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorText: errorText
                });
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            console.log('📋 API response data:', data);

            if (data.errorCode !== '0') {
                const errorMessages = {
                    '108': 'appKey无效',
                    '202': '签名检验失败',
                    '301': '账户余额不足',
                    '411': '访问频率受限',
                    '501': '请求的query为空',
                    '901': '翻译语种不支持'
                };
                const errorMsg = errorMessages[data.errorCode] || `API Error: ${data.errorCode}`;
                throw new Error(errorMsg);
            }

            const translation = data.translation?.[0] || '';
            console.log('✅ Direct API call successful:', {
                originalLength: processedText.length,
                translationLength: translation.length
            });

            return translation;

        } catch (error) {
            console.error('❌ Direct API call failed:', error);
            throw error;
        }
    }

    /**
     * 预处理文本
     */
    preprocessText(text) {
        if (!text || typeof text !== 'string') {
            return text;
        }

        let processed = text;
        // 移除控制字符
        processed = processed.replace(/[\u0000-\u001F\u007F-\u009F]/g, '');
        // 处理HTML实体
        processed = processed.replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"');
        // 处理空白字符
        processed = processed.replace(/\s+/g, ' ').trim();

        return processed || text;
    }

    /**
     * 生成UUID
     */
    generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    /**
     * 生成有道v3签名
     */
    async generateYoudaoSignV3(query, salt, curtime, appKey, appSecret) {
        const str = appKey + query + salt + curtime + appSecret;
        const encoder = new TextEncoder();
        const data = encoder.encode(str);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }

    // 检查扩展上下文是否有效
    isExtensionContextValid() {
        try {
            // 尝试访问扩展API，如果失败说明上下文已失效
            return chrome && chrome.runtime && chrome.runtime.id;
        } catch (error) {
            return false;
        }
    }

    // 安全地发送消息
    safeSendMessage(message, callback) {
        if (!this.isExtensionContextValid()) {
            callback({ success: false, error: '扩展上下文已失效' });
            return;
        }

        try {
            chrome.runtime.sendMessage(message, (response) => {
                if (chrome.runtime.lastError) {
                    callback({ success: false, error: chrome.runtime.lastError.message });
                } else {
                    callback(response);
                }
            });
        } catch (error) {
            callback({ success: false, error: error.message });
        }
    }

    /**
     * 渲染翻译结果
     */
    async renderTranslationResults(sections, results) {
        console.log('🎨 Rendering translation results...');
        console.log('📋 Sections count:', sections.length);
        console.log('📋 Results count:', results.length);
        console.log('📋 Results[0]:', results[0] ? 'has text' : 'empty');

        // 简化：现在results是一个字符串数组，每个元素都是相同的翻译结果
        if (results && results[0]) {
            const translatedText = results[0];
            console.log('📝 Translated text length:', translatedText.length);
            console.log('📝 Translated text preview:', translatedText.substring(0, 100) + '...');

            // 确保配置已加载
            if (!this.config) {
                this.config = await this.getCurrentConfig();
                console.log('🔧 Loaded config for rendering:', this.config);
            }

            console.log('🎯 Display mode:', this.config.displayMode);

            // 如果是替换模式，直接替换整个题目内容
            if (this.config.displayMode === 'replace') {
                const originalElement = sections[0].element;
                if (originalElement) {
                    console.log('🔄 Using replace mode, replacing element:', originalElement);
                    this.replaceProblemStatement(originalElement, translatedText);
                } else {
                    console.error('❌ No original element found for replacement');
                }
            } else {
                // 其他模式：为每个section渲染翻译
                console.log('🔄 Using non-replace mode');
                sections.forEach((section) => {
                    this.renderTranslation(section, translatedText);
                    this.translatedSections.add(section.element);
                });
            }
        } else {
            console.error('❌ No translation results to render');
        }

        console.log('✅ Translation results rendered');
    }

    /**
     * 替换整个题目陈述
     */
    replaceProblemStatement(originalElement, translatedText) {
        console.log('🔄 Replacing problem statement with translation');

        // 创建替换容器
        const replaceContainer = document.createElement('div');
        replaceContainer.className = 'translator-replace-container';
        replaceContainer.style.cssText = `
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin: 10px 0;
            padding: 15px;
        `;

        replaceContainer.innerHTML = `
            <div class="translator-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #dee2e6;">
                <span style="font-weight: bold; color: #495057;">🌐 中文翻译</span>
                <div class="translator-actions">
                    <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(originalElement.textContent)}\`)" style="margin-right: 5px; padding: 4px 8px; font-size: 12px; border: 1px solid #007bff; background: #007bff; color: white; border-radius: 3px; cursor: pointer;">复制原文</button>
                    <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(translatedText)}\`)" style="margin-right: 5px; padding: 4px 8px; font-size: 12px; border: 1px solid #28a745; background: #28a745; color: white; border-radius: 3px; cursor: pointer;">复制译文</button>
                    <button class="translator-btn toggle-btn" data-original="true" style="padding: 4px 8px; font-size: 12px; border: 1px solid #6c757d; background: #6c757d; color: white; border-radius: 3px; cursor: pointer;">显示原文</button>
                </div>
            </div>
            <div class="translator-content">
                <div class="translator-translated" style="display: block; white-space: pre-wrap; line-height: 1.5;">
                    ${this.escapeHtml(translatedText)}
                </div>
                <div class="translator-original" style="display: none; white-space: pre-wrap; line-height: 1.5;">
                    ${this.escapeHtml(originalElement.textContent)}
                </div>
            </div>
        `;

        // 替换原元素
        originalElement.parentNode.replaceChild(replaceContainer, originalElement);

        // 添加切换功能
        const toggleBtn = replaceContainer.querySelector('.toggle-btn');
        const originalDiv = replaceContainer.querySelector('.translator-original');
        const translatedDiv = replaceContainer.querySelector('.translator-translated');

        toggleBtn.addEventListener('click', () => {
            const isShowingOriginal = toggleBtn.getAttribute('data-original') === 'true';

            if (isShowingOriginal) {
                originalDiv.style.display = 'block';
                translatedDiv.style.display = 'none';
                toggleBtn.textContent = '显示翻译';
                toggleBtn.setAttribute('data-original', 'false');
            } else {
                originalDiv.style.display = 'none';
                translatedDiv.style.display = 'block';
                toggleBtn.textContent = '显示原文';
                toggleBtn.setAttribute('data-original', 'true');
            }
        });

        console.log('✅ Problem statement replaced successfully');
    }

    /**
     * 渲染单个翻译结果
     */
    renderTranslation(section, translatedText) {
        const { element, type } = section;

        // 创建翻译容器
        const translationContainer = document.createElement('div');
        translationContainer.className = 'translator-container';

        // 根据显示模式决定布局
        if (this.config.displayMode === 'below') {
            this.renderBelowMode(element, translationContainer, translatedText, type);
        } else if (this.config.displayMode === 'side') {
            this.renderSideMode(element, translationContainer, translatedText, type);
        } else {
            this.renderReplaceMode(element, translatedText);
        }
    }

    /**
     * 下方显示模式
     */
    renderBelowMode(originalElement, container, translatedText, type) {
        container.innerHTML = `
            <div class="translator-section">
                <div class="translator-header">
                    <span class="translator-label">🌐 ${this.getTypeLabel(type)}</span>
                    <div class="translator-actions">
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(originalElement.textContent)}\`)">复制原文</button>
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(translatedText)}\`)">复制译文</button>
                        <button class="translator-btn toggle-btn">▼</button>
                    </div>
                </div>
                <div class="translator-content">
                    <div class="translator-original">
                        <h4>原文:</h4>
                        <div>${this.escapeHtml(originalElement.textContent)}</div>
                    </div>
                    <div class="translator-translated">
                        <h4>译文:</h4>
                        <div>${this.escapeHtml(translatedText)}</div>
                    </div>
                </div>
            </div>
        `;

        // 插入到原元素后面
        originalElement.parentNode.insertBefore(container, originalElement.nextSibling);

        // 添加折叠功能
        this.setupToggleFunctionality(container);
    }

    /**
     * 并排显示模式
     */
    renderSideMode(originalElement, container, translatedText, type) {
        container.innerHTML = `
            <div class="translator-section translator-side-mode">
                <div class="translator-header">
                    <span class="translator-label">🌐 ${this.getTypeLabel(type)}</span>
                    <div class="translator-actions">
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(originalElement.textContent)}\`)">复制原文</button>
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(translatedText)}\`)">复制译文</button>
                        <button class="translator-btn toggle-btn">▼</button>
                    </div>
                </div>
                <div class="translator-content translator-content-side">
                    <div class="translator-original">
                        <h4>原文:</h4>
                        <div>${this.escapeHtml(originalElement.textContent)}</div>
                    </div>
                    <div class="translator-translated">
                        <h4>译文:</h4>
                        <div>${this.escapeHtml(translatedText)}</div>
                    </div>
                </div>
            </div>
        `;

        // 插入到原元素后面
        originalElement.parentNode.insertBefore(container, originalElement.nextSibling);

        // 添加折叠功能
        this.setupToggleFunctionality(container);
    }

    /**
     * 替换模式
     */
    renderReplaceMode(originalElement, translatedText) {
        // 创建替换容器
        const replaceContainer = document.createElement('div');
        replaceContainer.className = 'translator-replace-container';

        replaceContainer.innerHTML = `
            <div class="translator-section">
                <div class="translator-header">
                    <span class="translator-label">🌐 翻译结果</span>
                    <div class="translator-actions">
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(originalElement.textContent)}\`)">复制原文</button>
                        <button class="translator-btn" onclick="navigator.clipboard.writeText(\`${this.escapeHtml(translatedText)}\`)">复制译文</button>
                        <button class="translator-btn toggle-btn" data-original="true">显示原文</button>
                    </div>
                </div>
                <div class="translator-content">
                    <div class="translator-translated" style="display: block;">
                        <div>${this.escapeHtml(translatedText)}</div>
                    </div>
                    <div class="translator-original" style="display: none;">
                        <div>${this.escapeHtml(originalElement.textContent)}</div>
                    </div>
                </div>
            </div>
        `;

        // 替换原元素
        originalElement.parentNode.replaceChild(replaceContainer, originalElement);

        // 添加切换功能
        const toggleBtn = replaceContainer.querySelector('.toggle-btn');
        const originalDiv = replaceContainer.querySelector('.translator-original');
        const translatedDiv = replaceContainer.querySelector('.translator-translated');

        toggleBtn.addEventListener('click', () => {
            if (originalDiv.style.display === 'none') {
                originalDiv.style.display = 'block';
                translatedDiv.style.display = 'none';
                toggleBtn.textContent = '显示译文';
            } else {
                originalDiv.style.display = 'none';
                translatedDiv.style.display = 'block';
                toggleBtn.textContent = '显示原文';
            }
        });
    }

    /**
     * 设置折叠功能
     */
    setupToggleFunctionality(container) {
        const toggleBtn = container.querySelector('.toggle-btn');
        const content = container.querySelector('.translator-content');
        let isCollapsed = false;

        toggleBtn.addEventListener('click', () => {
            isCollapsed = !isCollapsed;
            if (isCollapsed) {
                content.style.display = 'none';
                toggleBtn.textContent = '▶';
            } else {
                content.style.display = 'block';
                toggleBtn.textContent = '▼';
            }
        });
    }

    /**
     * 获取类型标签
     */
    getTypeLabel(type) {
        const labels = {
            'title': '标题',
            'statement': '问题描述',
            'input': '输入格式',
            'output': '输出格式',
            'sample-input': '样例输入',
            'sample-output': '样例输出',
            'note': '注意事项'
        };
        return labels[type] || '翻译';
    }

    /**
     * HTML转义
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 显示加载状态
     */
    showLoadingState() {
        if (!this.floatingButton) return;

        const btnText = this.floatingButton.querySelector('.translator-btn-text');
        if (btnText) {
            btnText.innerHTML = '<div class="translator-spinner"></div>';
        }

        // 添加加载动画样式
        if (!document.getElementById('translator-loading-style')) {
            const style = document.createElement('style');
            style.id = 'translator-loading-style';
            style.textContent = `
                .translator-spinner {
                    width: 16px;
                    height: 16px;
                    border: 2px solid #ffffff;
                    border-top: 2px solid transparent;
                    border-radius: 50%;
                    animation: translator-spin 1s linear infinite;
                    margin: 0 auto;
                }
                @keyframes translator-spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            `;
            document.head.appendChild(style);
        }
    }

    /**
     * 隐藏加载状态
     */
    hideLoadingState() {
        if (!this.floatingButton) return;

        const btnText = this.floatingButton.querySelector('.translator-btn-text');
        if (btnText) {
            btnText.textContent = '翻译';
        }
    }

    /**
     * 显示成功消息
     */
    showSuccessMessage() {
        this.showToast('✅ 翻译完成', 'success');
    }

    /**
     * 显示错误消息
     */
    showError(message) {
        this.showToast('❌ ' + message, 'error');
    }

    /**
     * 显示提示消息
     */
    showToast(message, type = 'info') {
        // 移除现有toast
        const existingToast = document.getElementById('translator-toast');
        if (existingToast) {
            existingToast.remove();
        }

        const toast = document.createElement('div');
        toast.id = 'translator-toast';
        toast.textContent = message;

        // 设置样式
        const backgroundColor = {
            'success': '#28a745',
            'error': '#dc3545',
            'info': '#17a2b8'
        }[type] || '#17a2b8';

        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${backgroundColor};
            color: white;
            padding: 12px 20px;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 10001;
            font-size: 14px;
            font-weight: 500;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
        `;

        document.body.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateY(0)';
        }, 100);

        // 自动消失
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-20px)';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    /**
     * 查找输入格式部分（AtCoder 专用）
     */
    findInputSection(statementElement) {
        try {
            // 方法1: 查找包含"入力"或"Input"的h3标题
            const inputHeaders = statementElement.querySelectorAll('h3');
            for (const header of inputHeaders) {
                const text = header.textContent || '';
                if (text.includes('入力') || text.includes('Input') || text.includes('入力形式')) {
                    return header;
                }
            }

            // 方法2: 查找var标签后面跟着pre的情况
            const vars = statementElement.querySelectorAll('var');
            for (const varElement of vars) {
                const nextSibling = varElement.nextElementSibling;
                if (nextSibling && nextSibling.tagName === 'PRE') {
                    return varElement;
                }
            }

            // 方法3: 查找所有h3，检查其后兄弟元素是否包含pre
            const allHeaders = statementElement.querySelectorAll('h3, h2');
            for (const header of allHeaders) {
                const nextElement = header.nextElementSibling;
                if (nextElement && (nextElement.tagName === 'DIV' || nextElement.tagName === 'PRE')) {
                    // 检查是否包含代码块
                    const preElement = nextElement.tagName === 'PRE' ?
                        nextElement : nextElement.querySelector('pre');
                    if (preElement) {
                        // 检查标题内容，排除输出和样例
                        const headerText = header.textContent || '';
                        if (!headerText.includes('出力') &&
                            !headerText.includes('Output') &&
                            !headerText.includes('Sample') &&
                            !headerText.includes('出力例') &&
                            !headerText.includes('入出力例')) {
                            return header;
                        }
                    }
                }
            }

            return null;
        } catch (error) {
            console.warn('Error finding input section:', error);
            return null;
        }
    }

    /**
     * 查找输出格式部分（AtCoder 专用）
     */
    findOutputSection(statementElement) {
        try {
            // 查找包含"出力"或"Output"的h3标题
            const outputHeaders = statementElement.querySelectorAll('h3');
            for (const header of outputHeaders) {
                const text = header.textContent || '';
                if (text.includes('出力') || text.includes('Output') || text.includes('出力形式')) {
                    return header;
                }
            }

            // 如果没找到h3，查找h2
            const h2Headers = statementElement.querySelectorAll('h2');
            for (const header of h2Headers) {
                const text = header.textContent || '';
                if (text.includes('出力') || text.includes('Output')) {
                    return header;
                }
            }

            return null;
        } catch (error) {
            console.warn('Error finding output section:', error);
            return null;
        }
    }

    /**
     * 查找样例输入输出（AtCoder 专用）
     */
    findSampleTests(statementElement) {
        const samples = [];

        try {
            // 查找所有包含"入力例"和"出力例"的部分
            const headers = statementElement.querySelectorAll('h3, h2');

            let currentInput = null;
            let currentOutput = null;
            let sampleIndex = 0;

            for (let i = 0; i < headers.length; i++) {
                const header = headers[i];
                const text = header.textContent || '';

                if (text.includes('入力例') || text.includes('Sample Input')) {
                    const nextElement = header.nextElementSibling;
                    if (nextElement && nextElement.tagName === 'PRE') {
                        currentInput = nextElement;
                        sampleIndex++;
                    }
                }

                if (text.includes('出力例') || text.includes('Sample Output') && currentInput) {
                    const nextElement = header.nextElementSibling;
                    if (nextElement && nextElement.tagName === 'PRE') {
                        currentOutput = nextElement;

                        // 添加找到的样例对
                        samples.push({
                            input: currentInput,
                            output: currentOutput,
                            index: sampleIndex
                        });

                        currentInput = null;
                        currentOutput = null;
                    }
                }
            }

            return samples;
        } catch (error) {
            console.warn('Error finding sample tests:', error);
            return samples;
        }
    }

    /**
     * 销毁实例，清理事件监听器
     */
    destroy() {
        if (this.messageListener) {
            chrome.runtime.onMessage.removeListener(this.messageListener);
        }

        if (this.floatingButton && this.floatingButton.parentNode) {
            this.floatingButton.parentNode.removeChild(this.floatingButton);
        }

        // 清理翻译结果
        this.translatedSections.clear();
    }

    /**
     * 获取当前配置
     */
    async getCurrentConfig() {
        try {
            return await chrome.storage.sync.get({
                translationEngine: 'openai',
                sourceLanguage: 'auto',
                targetLanguage: 'zh-CN',
                displayMode: 'replace',
                autoTranslate: false
            });
        } catch (error) {
            console.error('Failed to get current config:', error);
            // 返回默认配置
            return {
                translationEngine: 'openai',
                sourceLanguage: 'auto',
                targetLanguage: 'zh-CN',
                displayMode: 'replace',
                autoTranslate: false
            };
        }
    }
}

// 初始化内容翻译器
try {
    new ContentTranslator();
} catch (error) {
    console.error('Failed to start content translator:', error);
}